import CryptoJS from "crypto-js";
import axios from "axios";
import express from "express";

const app = express();
const KEY_PWD = process.env.DES_CMS_KEY; // or replace with your DES_CMS_KEY

function encryptUrl(input) {
  let CIPHER_ALGORITHM = "DES-CBC";
  let IV_SIZE = 8;
  try {
    const keyBytes = CryptoJS.enc.Utf8.parse(KEY_PWD);
    const inputBytes = CryptoJS.enc.Utf8.parse(input);
    const ivBytes = CryptoJS.lib.WordArray.random(IV_SIZE);
    const encrypted = CryptoJS.DES.encrypt(inputBytes, keyBytes, {
      iv: ivBytes,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7,
    });
    const ciphertext = ivBytes.concat(encrypted.ciphertext);
    return ciphertext.toString();
  } catch (error) {
    console.error(error);
    return null;
  }
}

app.use("/blog/:id", async (req, res, next) => {
  if (req.params.id === "author" || req.params.id === "topics") {
    next();
  } else {
    const postId = "/" + req.params.id;
    let obj = {
      id: postId,
      packageName: "WebTt",
    };
    let encryptedId = encryptUrl(JSON.stringify(obj));
    try {
      const response = await axios.post(
        `https://savingtik.com/js/a/api/cms/web/articleDetailById`,
        { condition: encryptedId },
        {
          headers: { "Content-Type": "application/json" },
        }
      );
      if (response.data.code !== 200) {
        res.status(404).end();
      } else {
        next();
      }
    } catch (error) {
      next(error);
    }
  }
});

module.exports = app;
